package com.yifeng.repo.micro.service.server.engine.request.openx;

import com.yifeng.repo.base.utils.servlet.AbstractFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * Created by daibing on 2023/3/14.
 */
@Slf4j
public class JsonRequestFilter extends AbstractFilter {

    public JsonRequestFilter(List<String> excludeUris) {
        super(excludeUris.toArray(new String[0]));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取request
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 2. 排除uri
        if (this.isExcludeUri(request.getRequestURI().toLowerCase())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 3. Wrapper支持重复读取body的场景
        if (request.getMethod().equals(HttpMethod.POST.toString())) {
            filterChain.doFilter(new JsonRequestWrapper(request), servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
